#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2016 lizongzhe 
#
# Distributed under terms of the MIT license.

from proxy_manager import core, resource
from django.core.cache import cache
import random
import time


#resource_list = [r.ProxyResource('CN', 'https') for r in resource.RESOURCE_LIST]
#resource_list = [resource.proxy_mimvp_prive.ProxyResource('860160715151231159', 'CN', 'https')]
#resource_list = [resource.proxy_kuaidaili_prive.ProxyResource('926953786244852', ('goblin.george', '793jdoq2'), 10), resource.proxy_mimvp_prive.ProxyResource('860160715151231159', 'CN', 'https', 20)]


class ProxyLock():
    _capture = None
    def __init__(self):
        self.key = random.randint(0, 10000)
        resource_list = [resource.proxy_kuaidaili_public.ProxyResource()]
        self.proxy_manager = core.ProxyManager(resources=resource_list)


    def lock(self):
        while True:
            key = cache.get('proxy_lock')
            if key and key != self.key:
                time.sleep(1)
            elif key == self.key:
                return 
            else:
                cache.set('proxy_lock', self.key, 60)

    def unlock(self):
        cache.set('proxy_lock', None)

    def _get(self):
        proxy_pool = cache.get('proxy_pool')
        if not proxy_pool:
            self.update_proxy()
            proxy_pool = cache.get('proxy_pool')
        proxy = core.to_proxyhost(proxy_pool[0])
        cache.set('proxy_pool', proxy_pool[1:])
        return proxy

    def update_proxy(self):
        while True:
            try:
                proxy_pool = [core.to_dict(p) for p in self.proxy_manager.crawl_proxies()]
                cache.set('proxy_pool', proxy_pool)
                return
            except Exception as e:
                pass

    def get(self):
        if self._capture:
            proxy = self._capture
            self._capture = None
            return proxy
        self.lock()
        proxy = self._get()
        self.unlock()
        return proxy

    def capture(self, proxy):
        self._capture = proxy


proxy_lock = ProxyLock()

def get():
    proxy_host = proxy_lock.get()
    return proxy_host

def capture(proxy):
    proxy_lock.capture(proxy)
